from django.http import HttpResponse
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
from django_redis import get_redis_connection
from .serializers import RegisterSmscodeSerilizer

# Create your views here.


class RegisterImagecodeAPIView(APIView):

    def get(self,request,image_code_id):
        #1.调用第三方库生成图片验证码
        text,image = captcha.generate_captcha()
        #2.链接redis数据库并将验证码内容保存，有效时间300s
        redis = get_redis_connection('code')
        redis.setex('img_%s'%image_code_id,300,text)
        #3.返回验证码图片给前端
        return HttpResponse(content=image,content_type='image/jpeg')


class RegisterSmscodeAPIView(GenericAPIView):

    serializer_class = RegisterSmscodeSerilizer

    def get(self,request,mobile):
        #1.接收前端数据
        params = request.query_params
        #2.调用序列化器做参数校验
        serializer = self.get_serializer(data=params)
        serializer.is_valid(raise_exception=True)
        #3.生成短信验证码
        import random
        sms_code = '%06d'%random.randint(0,999999)

        #采用常规方式处理信息发送任务
        #4.调用第三方库发送短信
        # ret = CCP().send_template_sms(mobile,[sms_code,5],1)
        #
        # #5.如果发送成功，将验证码信息存储到redis中
        # if ret:
        #     return Response({'message':'验证码发送失败'})
        # else:
        #     redis = get_redis_connection('code')
        #     redis.setex('sms_%s'%mobile,5*60,sms_code)
        #     return Response({'message':'OK'})

        #采用celery异步方式处理信息发送任务
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile,sms_code)

        redis = get_redis_connection('code')
        redis.setex('sms_%s'%mobile,5*60,sms_code)
        return Response({'message':'OK'})











